package com.dataseek.iot.toolkit.auth.util;


import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
    //有效期为
    public static final Long JWT_TTL=24*60*60*1000L;
    //设置秘钥明文
    public static final String JWT_KEY="Dataseek";

    public static String getUUID(){
        String token = UUID.randomUUID().toString().replaceAll("-","");
        return token;
    }

    public static String createJWT(String subject){
        JwtBuilder builder = getJwtBuilder(subject,null,getUUID());
        return  builder.compact();
    }

    public static String createJWT(String id,String subject,Long ttlMills){
        JwtBuilder builder = getJwtBuilder(subject,ttlMills,id);
        return  builder.compact();
    }

    private static JwtBuilder getJwtBuilder(String subject,Long ttlMills,String uuid){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        SecretKey secretKey = generalKey();
        Long nowMills = System.currentTimeMillis();
        Date now = new Date(nowMills);
        if(ttlMills==null){
            ttlMills=JwtUtil.JWT_TTL;
        }
        Long expMills = nowMills+ttlMills;
        Date expDate = new Date(expMills);
        return Jwts.builder()
                .setId(uuid)
                .setSubject(subject)
                .setIssuer("dataseek")
                .setIssuedAt(now)
                .signWith(signatureAlgorithm,secretKey)
                .setExpiration(expDate);
    }

    /**
     * 生成加密后的秘钥
     */
    public static SecretKey generalKey(){
        byte[] encodedKey = Base64.getDecoder().decode(JwtUtil.JWT_KEY);
        SecretKey key = new SecretKeySpec(encodedKey,0, encodedKey.length, "AES");
        return key;
    }

    /**
     * 解析
     * @param jwt
     * @return
     * @throws Exception
     */
    public static Claims parseJWT(String jwt) throws Exception{
        SecretKey secretKey = generalKey();
        return Jwts.parser().setSigningKey(secretKey).parseClaimsJws(jwt).getBody();
    }


}
